<template>
  <div>
    <el-upload
      v-loading="loadingFlag"
      :action="fileUrl"
      class="avatar-uploader"
      :show-file-list="false"
      :on-change="handleChange"
      :on-error="handleError"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
    >
      <img v-if="pictureUrl" :src="staticImgUrl+pictureUrl" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
  </div>
</template>

<script>
import { fileUrl, staticImgUrl } from '@/url'
export default {
  name: 'UploadImage',
  props: {
    url: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      fileUrl: fileUrl,
      staticImgUrl: staticImgUrl,
      pictureUrl: '',
      loadingFlag: false

    }
  },

  watch: {

    url: {
      immediate: true,
      handler: function(newval, oldval) {
        if (newval !== oldval) {
          this.pictureUrl = newval
        }
      }
    }
  },
  created() {
    if (this.url) this.pictureUrl = this.url
  },
  methods: {
    handleError() {
      this.loadingFlag = false
    },
    handleChange(file) {
      if (file.status === 'success') {
        setTimeout(() => {
          this.loadingFlag = false
        }, 500)
      } else {
        this.loadingFlag = true
      }
    },
    getImagesUrl() {
      return this.pictureUrl
    },
    handleAvatarSuccess(res, file) {
      const picture = res.picture_url
      this.pictureUrl = picture
      this.$emit('setUrl', picture)
    },
    beforeAvatarUpload(file) {
      // console.log(file.type)
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt6M = file.size / 1024 / 1024 < 6
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!')
        this.loadingFlag = false
      }
      if (!isLt6M) {
        this.$message.error('上传头像图片大小不能超过 6MB!')
        this.loadingFlag = false
      }
      return isJPG && isLt6M
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
